<template>
	<view>
		<!-- header -->
		<div class="page-header" style="height:170px;">
			<div class="title-header">
				<template v-if="ifHome===true">
					<div style="min-width:40px;">&nbsp;</div>
				</template>
				<template v-else>
					<div class="-goback" @click="goHome()">&nbsp;</div>
				</template>
				<div class="-title">{{mpTitle}}</div>
			</div>
		</div>
		<div class="background-circle"></div>

		<!-- 用户卡片 -->
		<div v-if="userInfo" class="-user-card">
			<template v-if="logined">
				<div class="-avatar" @click="goAccount()">
					<img :src="userInfo.avatar" />
				</div>
			</template>
			<template v-else>
				<div class="-avatar" @click="login()">
					<img :src="defaultAvatar" />
				</div>
			</template>
			<div class="-nickname">
				<template v-if="logined">
					<div @tap="goAccount()">{{userInfo.nickName}}</div>
				</template>
				<template v-else>
					<div @tap="login">请登录</div>
				</template>

				<div class="text-small">{{hasPhone?userInfo.phone:''}}</div>
			</div>
		</div>

		<!-- 底部菜单 -->
		<view class="global-menu">
			<template v-for="(item,index) in menuList">
				<view @tap="handleItemClick(item,index)" :class="activeIndex===index?'item active':'item'">
					<uni-icons :color="activeIndex===index?activeColor:idleColor" :type="item.icon"
						size='25'></uni-icons>
					<view>{{item.label}}</view>
				</view>
			</template>
		</view>

		<!-- 开门按钮 -->
		<view v-if='showDoorBtn' :class="canOpenDoor===true?'btn-door btnActive':'btn-door'">
			<template v-if="canOpenDoor===true">
				<template v-if="logined===true">
					<!-- 一登录 -->
					<view @tap="handleDoorOpen">
						<uni-icons color='white' type='scan' size='30'></uni-icons>
						<view>确认开门</view>
					</view>
				</template>
				<template v-else>
					<!-- 未登录 -->
					<view @tap="loginThenDoorOpen">
						<uni-icons color='white' type='scan' size='30'></uni-icons>
						<view>确认开门</view>
					</view>
				</template>
			</template>
			<template v-else>
				<view @tap="doorButton">
					<uni-icons color='white' type='scan' size='30'></uni-icons>
					<view>扫码开门</view>
				</view>
			</template>
		</view>

		<!-- 授权登陆窗 -->
		<template v-if="showLoginWindow===true">
			<div class="loginWindow">
				<div class="inner">
					<div class="title">请点击授权小程序授权登录</div>
					<div class="body">点击小程序授权登录按钮,可以使用小程序授权手机号登录</div>
					<div class="confrimBtn">
						<button class="confirm" open-type="getPhoneNumber"
							@getphonenumber="getPhoneNumber">小程序授权登录</button>
						<button class="cancle" @tap="showLoginWindow=false">取消</button>
					</div>
				</div>
			</div>
		</template>

		<!-- 底部弹出层 -->
		<view v-if="showDoorSuccess===true" class="doorSuccess">
			<view class="inner">
				<view style="font-size: large;text-align: center;">正在开锁...</view>
				<view style="font-size: small;color:lightgray;text-align: center;">请留意门锁状态</view>
				<view>
					<img class="unlockImg" :src="unlockImg" />
				</view>
				<view style="margin:15px 25px;">
					<button @tap="goHome" type="primary">返回</button>
				</view>
			</view>
		</view>

		<!-- 扫码登录成功弹出层 -->
		<view v-if="showLoginSuccess===true" class="doorSuccess">
			<view class="inner">
				<template v-if="loginSuccess!==true">
					<view style="font-size: large; text-align: center;">请确认登录</view>
					<view style="font-size: small;color:lightgray;text-align: center;">点击按钮确认登录</view>
					<view style="text-align: center;">
						<view class="btnSelfLogin" @tap="selfLogin">
							<view>
								<uni-icons color="white" type="auth" size="60"></uni-icons>
								<view>
									<text>授权登录</text>
								</view>
							</view>
						</view>
					</view>
					<view style="margin:15px 25px;text-align: center;font-size: small;">
						<text @tap="goHome" style="color:coral;">取消并返回</text>
					</view>
				</template>
				<template v-else>
					<view style="font-size: large; text-align: center;">请求已发送</view>
					<view style="color:seagreen;text-align: center;margin:70px auto;">已授权登录，请在自助机上继续操作。</view>
					<view style="margin:15px 25px;">
						<button @tap="goHome" type="primary">返回</button>
					</view>
				</template>
			</view>
		</view>
	</view>
</template>

<script>
	import com from '@/common/index.js'
	import {
		nextTick,
		watch
	} from 'vue';
	export default {
		name: "global-menu",
		props: {
			//true将显示开门按钮，否则是扫码开门
			canOpenDoor: {
				type: Boolean,
				default: false
			},
			//openDoor页面的参数
			options: {
				type: Object,
				default: {}
			},
			//登录状态改变 
			onLoginStatusChange: {
				type: Function,
				required: true
			}
		},
		data() {
			return {
				showLoginSuccess: false, //是否显示自助机成功登录底部弹窗
				loginSuccess: false, //自助机登录弹窗内容状态 true一登录成功，false显示自助机登录按钮
				showDoorSuccess: false, //是否显示开门成功底部弹窗
				logined: false, //是否已登录
				ifHome: false, //是否在首页
				mpTitle: com.mpTitle,
				defaultAvatar: "/static/images/avatar.jpeg",
				unlockImg: "/static/images/unlock.gif",
				hasPhone: false, //是否有手机号
				userInfo: {},
				showLoginWindow: false, //权限窗口
				loginData: {},
				//是否显示开门按钮
				showDoorBtn: false,
				//true?开门:扫码开门
				showOpenDoor: false,
				//菜单项
				menuList: [{
						label: '首页',
						icon: 'home',
						page: '/pages/userhome'
					},
					{
						label: '我的',
						icon: 'person',
						page: ''
					},
				],
				activeColor: '#4a7afe',
				idleColor: '#454545',
				activeIndex: 0,
				defaultAvatar: "/static/images/avatar.png",

			};
		},
		onLocreated() {
			console.log('组件创建了');
		},
		mounted() {
			console.log('组件挂载了');
			//this.showDoorSuccess=true //测试开锁弹窗
			const page = com.currentPages()
			this.ifHome = page.indexOf('userhome') >= 0 //是否是首页
			const d = com.getUserInfo()
			console.log('user:', d)
			//debugger
			if (d) {
				this.logined = true
				this.userInfo = d
				if (d.phone && d.phone !== '') this.hasPhone = true
			}
			this.getButton()
			//console.log('opt:',this.options)
			//自助机扫码登录页,开启底部弹窗
			this.showLoginSuccess = (page.indexOf('scanLogin') && this.options.t == '2')

		},
		onLoad() {
			console.log('onLoad 方法执行了');
		},
		methods: {
			//更新用户信息
			userDataUpdate() {
				const that = this
				try {
					let res = com.getUserInfo()
					that.userInfo = res ? res : {}
					that.$emit('onLoginStatusChange', res)
				} catch (err) {
					console.log(err)
					console.log('更新用户信息失败(global-menu)')
				}
			},
			loginThenDoorOpen() {
				const that = this
				this.login()
				let max = 30
				let si = setInterval(() => {
					if (max <= 0) {
						clearInterval(si)
						uni.showToast({
							title: "操作失败,请重试",
							icon: 'none',
							duration: 4000
						})
					} else {
						console.log('倒数等待:', max)
						max -= 1
						if (that.logined === true && that.hasPhone === true) {
							//开门得有电话  
							clearInterval(si)
							console.log('已登录完毕,执行开门')
							setTimeout(() => {
								that.handleDoorOpen()
							}, 1000)
						}
					}
				}, 500)
			},
			goHome() {
				uni.navigateTo({
					url: "/pages/userhome"
				})
			},
			//确认开门按钮点击
			handleDoorOpen() {
				const that = this
				//debugger
				///mapi/scan-code/open-door
				if (!that.options.c) {
					console.log('没有c:', that.options)
					uni.showToast({
						title: '参数错误',
						icon: 'error'
					})
					return
				}
				//console.log('userInfo:', that.userInfo)
				//debugger
				const p = {
					id: that.options.c,
					uid: that.userInfo.uid
				}
				//console.log('p:', p)
				com.poster(
					"/mapi/scan-code/open-door?t=" + (new Date()).getTime(), p, "post", (e) => {
						if (e.code !== 200) {
							uni.showToast({
								title: e.msg,
								icon: "error",
								duration: 3000
							})
							return
						}

						console.log('已开门')
						//这里弹窗
						that.showDoorSuccess = true
					}, null, true)
			},
			handleItemClick(item, index) {
				this.activeIndex = index
				console.log('item:', item)
				if (item.page === '') return
				uni.navigateTo({
					url: item.page
				})
			},
			// 扫码开门按钮点击
			doorButton() {
				const that = this
				//需要登录
				if (this.logined !== true) {
					uni.showToast({
						title: '请先登录',
						icon: 'error'
					})
					return
				}

				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.camera']) {
							uni.authorize({
								scope: 'scope.camera',
								success() {
									// 用户已经同意过授权，现在可以调用扫一扫了
									that.scan()
								},
								fail() {
									// 用户拒绝了授权请求，或者没有设置过该权限，可以引导用户去设置中开启权限
									uni.showModal({
										title: '授权提示',
										content: '章鱼智阅舱需要使用相机权限，请在设置中授权',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												// 引导用户去设置页面授权，例如：
												uni
													.openSetting(); // 注意：在某些情况下（如微信小程序），直接打开设置页面可能不被允许，需引导用户手动进入设置页面进行授权。
											}
										}
									});
								}
							});
						} else {
							// 用户已经授权，直接调用扫一扫功能
							that.scan()
						}
					}
				});
				//this.openDoorLog(this.mct)
			},
			//扫码
			scan() {
				const that = this
				uni.scanCode({
					onlyFromCamera: true, //只允许使用相机
					success: (e) => {
						console.log('扫描结果:')
						console.log(e)
						if (e.errMsg !== "scanCode:ok") {
							uni.showToast({
								title: e.errMsg,
								icon: 'error'
							})
							return
						}
						if (e.path) {
							uni.navigateTo({
								url: '/' + e.path
							})
						}
					},
					fail(e) {
						uni.showToast({
							title: "不支持的二维码",
							icon: "error"
						})
					}
				});
			},
			// 是否显示开门按钮
			getButton() {
				const that = this
				uni.request({
					url: com.serviceURL + '/miniapi/bottom/show',
					method: 'GET',
					success: (e) => {
						if (e.data.code !== 200) {
							uni.showToast({
								title: e.msg,
								icon: 'error'
							})
							// com.clearUserInfo()
							// com.clearToken()
							// that.logined = false
							// that.hasPhone = false
							return
						}
						let val = e.data.data.is_show === 1
						console.log('已更改按钮显示状态:', val)
						that.showDoorBtn = true //val
					}
				})
			},

			// 根据二维码参数执行相应的业务逻辑
			doActions(params) {
				console.log('准备分配任务')
				const that = this
				/*
				m:机器码 已改成机器id***
				c:书室id
				t:
				1扫码开门, 2自助借还机扫码登录
				*/
				if (params.t === '1') {
					that.openDoorLog(params)
				} else if (params.t === '2') {
					that.deviceLoginLog(params)
				}
			},
			// 保存用户的自助借还机登录日志
			deviceLoginLog(p) {
				const that = this
				console.warn('自助借还机登录')
				return
				//miniapi/auth/device-login-log
				com.poster('/miniapi/auth/device-login-log', {
					t: p.t,
					m: p.m,
					c: p.c,
					a: p.a,
					biz_reader_info_id: that.userInfo.uid || com.getUserInfo().uid
				}, 'POST', (e) => {
					console.log(e)
					uni.showToast({
						title: e.msg,
						icon: e.code === 200 ? 'success' : 'error'
					})
				}, (e) => {
					console.log(e)
				})
			},
			// 保存用户的开门日志
			openDoorLog(p) {
				const that = this
				console.log('开门')
				return
				//that.userInfo.uid,com.getUserInfo().uid
				//miniapi/auth/open-door-log
				com.poster('/miniapi/auth/open-door-log', {
					t: p.t,
					m: p.m,
					c: p.c,
					biz_reader_info_id: that.userInfo.uid || com.getUserInfo().uid
				}, 'POST', (e) => {
					console.log(e)
					uni.showToast({
						title: e.msg,
						icon: e.code === 200 ? 'success' : 'error'
					})
				}, (e) => {
					console.log(e)
				})
			},

			getPhoneNumber(e) {
				const that = this
				let phonedata, phonedataiv
				//console.log(e)
				if (e.detail.errMsg !== 'getPhoneNumber:ok') return
				if (!that.loginData.session_key) {
					console.log('no keys');
					return
				}
				phonedata = e.detail.encryptedData;
				phonedataiv = e.detail.iv;
				uni.request({
					method: "POST",
					url: com.serviceURL + `/miniapi/auth/phone`,
					header: {
						'X-Mini-App-Id': com.getAppID(),
						'authorization': 'Bearer ' + com.getToken()
					},
					data: JSON.stringify({
						session_key: that.loginData.session_key,
						iv: phonedataiv,
						encrypted_data: phonedata
					}),
					success: (res) => {
						that.showLoginWindow = false
						console.log('获取手机号结果：')
						console.log(res)
						if (res.data.code !== 200) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
							return
						}
						that.userInfo.phone = res.data.data.phone
						that.hasPhone = true
						com.setUserInfo(that.userInfo)
						that.$emit('onLoginStatusChange', that.userInfo)
					},
					fail: (err) => {
						uni.showToast({
							title: err,
							icon: 'none'
						})
					}
				})
			},
			login() {
				if (this.logined === true) return
				uni.showLoading({
					title: "请稍后"
				})
				const that = this
				uni.getUserProfile({
					desc: '用于完善个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						const loginData = {
							iv: res.iv,
							session_key: "",
							encrypted_data: res.encryptedData
						}
						//that.userInfo = res.userInfo
						const userTmp = res.userInfo
						uni.login({
							success: (res) => {
								uni.hideLoading()
								console.log(res)
								if (res.errMsg !== 'login:ok') {
									uni.showToast({
										title: '操作失败',
										icon: 'none'
									})
									return
								}
								that.logined = true
								uni.request({
									method: "POST",
									url: com.serviceURL + `/miniapi/auth/login`,
									header: {
										'X-Mini-App-Id': com.getAppID()
									},
									data: JSON.stringify({
										code: res.code,
										avatarUrl: userTmp.avatarUrl,
										nickName: userTmp.nickName
									}),
									success: (res) => {
										if (res.data.code !== 200) {
											uni.showToast({
												title: res.data.msg,
												icon: 'none'
											})
											return
										}
										if (!that.userInfo) {
											that.userInfo = {}
										}
										that.userInfo.uid = res.data.data.uid
										that.userInfo.avatar = res.data.data.avatar
										that.userInfo.nickName = res.data.data.nickname
										console.log(that.userInfo)
										com.setToken(res.data.data.token)

										if (res.data.data.phone === '') {
											that.hasPhone = false
											// 无手机号
											console.log('获取用户手机号')
											loginData.session_key = res.data.data
												.session_key
											that.loginData = loginData
											com.setToken(res.data.data.token)
											that.showLoginWindow = true
										} else {
											//已有手机号
											that.hasPhone = true
											that.userInfo.phone = res.data.data.phone
											//console.log(that.userInfo)
											uni.showToast({
												title: res.data.msg,
												icon: 'none'
											})
											com.setUserInfo(that.userInfo)
											that.$emit('onLoginStatusChange', that
												.userInfo)
										}
									},
									fail: (err) => {
										uni.showToast({
											title: err,
											icon: 'none'
										})
									}
								});
							}
						})
					},
					fail: err => {
						uni.hideLoading()
						uni.showToast({
							title: err,
							icon: 'none'
						})
						console.log(err)
					}
				})
			},
			// 修改信息
			goAccount() {
				if (this.logined !== true) {
					uni.showToast({
						title: '请先登录',
						icon: 'error'
					})
					return
				}
				com.go('account')
			},
			//通知自助机登录
			selfLogin() {
				//data:
				// m_id: ps.m,
				// action: ps.a,
				// uid: user().uid
				///mapi/scan-code/device-turned-on
				const that = this

				function post() {
					let data = {
						m_id: that.options.m,
						action: that.options.a,
						uid: that.userInfo.uid
					}
					com.poster(
						"/mapi/scan-code/device-turned-on", data, "post", (e) => {
							console.log(e)
							if (e.code === 200) {
								that.loginSuccess = true
							} else {
								uni.showToast({
									title: e.msg,
									icon: 'error',
									duration: 4000
								})
							}
							uni.hideLoading()
						}, (e) => {
							uni.hideLoading()
						}, true)
				}
				if (that.logined !== true || that.hasPhone !== true) {
					//未登录
					that.login()
				}
				let max = 30
				let si = setInterval(() => {
					if (max <= 1) {
						clearInterval(si)
						uni.showToast({
							title: "操作失败,请重试",
							icon: 'none',
							duration: 4000
						})
					} else {
						console.log('倒数等待:', max)
						max -= 1
						if (that.logined === true && that.hasPhone === true) {
							clearInterval(si)
							console.log('已登录，执行自助机登录')
							setTimeout(() => {
								post()
							}, 1000)
						}
					}
				}, 500)
			}
		}
	}
</script>

<style>
	.btn-door {
		display: flex;
		align-items: center;
		position: fixed;
		bottom: 53px;
		width: 80px;
		height: 80px;
		z-index: 88;
		left: calc(50vw - 40px);
		border-radius: 10ex;
		/* box-shadow: 0 0 5px 2px rgba(0,0,0,.15); */
		box-shadow: 0 0 4px 2px rgba(0, 0, 0, .5);
		/*#4f7dfd;*/
		/* background-color: white; */
		justify-content: center;
		text-align: center;
		font-size: small;
		color: white;
		background-color: #4175fe;
	}

	.btn-door.btnActive {
		background-color: #41a863;
	}

	.global-menu {
		position: fixed;
		bottom: 0;
		display: flex;
		align-items: center;
		width: 100%;
		box-shadow: 0 0 1px 1px #4175fe;
		background-color: white;
		z-index: 87;
	}

	.global-menu>.item {
		flex: 1;
		padding: 15px 10px 10px 10px;
		text-align: center;
		margin-bottom: 15px;
		color: #454545;
	}

	.global-menu>.item.active {
		color: #4a7afe;
	}

	.doorSuccess {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		backdrop-filter: blur(5px);
		z-index: 100;
	}

	.doorSuccess .inner {
		background-color: white;
		min-height: 20vh;
		box-shadow: 0 0 3px 1px rgba(0, 0, 0, .7);
		padding: 25px 0;
		position: fixed;
		width: 100%;
		margin-bottom: 0;
		bottom: 0;
		z-index: 99;
		backdrop-filter: blur(5px);
	}

	.unlockImg {
		display: block;
		width: 110px;
		height: 110px;
		margin: 50px auto 30px auto;
	}

	.btnSelfLogin {
		border-radius: 1ex;
		box-shadow: 0 0 3px 1px rgba(0, 0, 0, .5);
		padding: 0 10 15px 10;
		width: 100px;
		height: 100px;
		margin: 40px auto;
		background-color: #4a7afe;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btnSelfLogin text {
		color: white;
		font-size: small;
	}
</style>